<?php

namespace App\Services\Api;

use App\Services\Admin\User;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Cache;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class EasyWeChatService
{
     public static function easy_app(){
         $config = [
             'app_id' => config('wechat.wx_appid'),
             'secret' => config('wechat.wx_appsecret'),
             // 下面为可选项
             // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
             'response_type' => 'array',

             'log' => [
                 'level' => 'debug',
                 'file' => __DIR__.'/wechat.log',
             ],
         ];
            //dd($config);
         return Factory::miniProgram($config);
     }

     //发送微信提醒消息
    public static function getAccessToken()
    {
        //获取微信openid
        $url = sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", env('WX_APPID'), env('WX_APPSECRET'));

        $client = new Client();
        $res = $client->request('GET', $url, ['timeout' => 3.5]);
        $res = $res->getBody();

        $res_openid = json_decode($res);

        return $res_openid->access_token ?? 0;
    }

    public static function getCashToken()
    {
        //获取access_token
        $access_token = '';
        if (!Cache::has('access_token_order')) {
            $access_token = self::getAccessToken();
            Cache::put('access_token_order', $access_token, 7200);
        } else {
            $access_token = Cache::get('access_token_order');
        }

        return $access_token;
    }

    /**
     * 发送消息
     * @param int $access_token
     * @param int $wx_openid
     */
    public static function sentMessage($access_token = 0, $wx_openid = 0, $data = [])
    {
        //  这里替换为你的 appID 和 appSecret
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";

        $template_id = env('WECHAT_TEMPLATE_MESSAGE');

        $post_data = [
            // 用户的 openID，可用过 wx.getUserInfo 获取
            "touser" => $wx_openid,

            // 小程序后台申添加的订阅消息模板 ID
            "template_id" => $template_id,

            "data" => $data,

            'page'=>''
        ];

        $client = new Client();

        $res = $client->post($url, [
            'headers' => ['Content-Type' => 'application/json'],//设置请求头为json
            'json' => $post_data
        ]);

        $body = $res->getBody()->getContents();

        $log = [
            'title' => 'we_chat_message_debug:'.$wx_openid,
            'url' => $url,
            'post_data' => $post_data,
            'body_errmsg' => $body
        ];

        Log::info(json_encode($log));

        if (isset($body->errmsg)) {
            if ($body->errmsg != 'ok') {
                //Log::info(json_encode($body));
            } else {
                //return true;
            }
        } else {
            //Log::info(json_encode($body));
        }
    }

    /**
     * @param int $user_id
     * @param int $wx_openid
     */
    public static function sendUserMessage($user_id = 0,  $data)
    {
        //处理data字符不能超过20个字符
        foreach ($data as &$v){
            if(isset($v['value'])) {
                if (mb_strlen($v['value']) > 20) {
                    $v['value'] = mb_substr($v['value'], 0, 17) . "...";
                }
            }
        }

        //发送消息
        $user_info = User::info($user_id);

        $access_token = self::getCashToken();

        self::sentMessage($access_token, $user_info->wx_openid, $data);
    }
}
